import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;






public class test2 {
	private static final String LOG_TAG = "ExampleApp";

    private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";

    private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
    private static final String TYPE_DETAILS = "/details";
    private static final String TYPE_SEARCH = "/textsearch";

    private static final String OUT_JSON = "/json";

    // KEY!
    private static final String API_KEY = "AIzaSyB8QPf2KSpG_El4HN8IrvJ3GsT5YBsnrd8";
    
	public test2() {
//		HttpURLConnection conn = null;
//        StringBuilder jsonResults = new StringBuilder();
//        try {
////            StringBuilder sb = new StringBuilder(PLACES_API_BASE);
////            sb.append(TYPE_DETAILS);
////            sb.append(OUT_JSON);
////            sb.append("?sensor=false");
////            sb.append("&key=" + API_KEY);
////            sb.append("&reference=" + "CoQBcgAAAMm-Wbqf-P4JoFqYq1wq6gB6Xp1K6EDx3_OeVwprHtdkIf70IFcZPLxf32B_VA8Mnuuanp79vMWurECp-fjqC30fyb4jpyKFTlI4RkuodXyKGTLtRuYLghWLLvepHLCZTEioXoj24uhXHLsr_fRQsb2jD0l2L-GLEWJWk53KqLYfEhDQZ9c_iw_RlLbQC4S7W_M7GhSI-XfRaS3ub9m45Q0O_EBHoiQTeA");
////            System.out.println(sb.toString());
//        	String code = URLEncoder.encode("29號, Section 2, Mínquán East Road, Zhongshan District","utf-8");
//        	
//            String str="http://maps.googleapis.com/maps/api/geocode/json?address="+code+"&sensor=true&language=zh-TW";
////            System.out.println(str);
//            URL url = new URL(str);
//            conn = (HttpURLConnection) url.openConnection();
//            InputStreamReader in = new InputStreamReader(conn.getInputStream());
//            
//            // Load the results into a StringBuilder
//            int read;
//            char[] buff = new char[1024];
//            while ((read = in.read(buff)) != -1) {
//                jsonResults.append(buff, 0, read);
//            }
//            System.out.println(jsonResults);
//        } catch (MalformedURLException e) {
//
//        } catch (IOException e) {
//
//        } finally {
//            if (conn != null) {
//                conn.disconnect();
//            }
//        }
		
		

		this.search(URLEncoder.encode("台北市中山區")+ "+" + URLEncoder.encode("美食"), 25.0688889,121.5330956, 5);
		
       
	}
	
	public void search(String keyword, double lat, double lng, int radius) {

		HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();
        try {
            StringBuilder sb = new StringBuilder(PLACES_API_BASE);
            sb.append(this.TYPE_SEARCH);
            sb.append(OUT_JSON);
//            sb.append("?reference=CoQBeQAAANRE-WQMj69hWoGwrDIAw2KjLWbdcFuZuNz5EvOKMY9FFvnnXMhicEWMD5QTo4Lf3MYY01qF67LoO_mQSOwYEI8lorszrx-mxE9S3RiM7GWrHa9YvLbgpLq0CtgZMvbUT13YJIM-rkci23T9_8laDXQHq_i56EYzLFMsgKkBvrvtEhD4RZMDmOcD87TAeR1gMMygGhTMrZLHzrbFthAWwft7hDhym5M5ew");
            sb.append("?query=" + keyword);
            sb.append("&sensor=true");
            sb.append("&key=" + API_KEY);

            //sb.append("&location=" + String.valueOf(lat) + "," + String.valueOf(lng));
            //sb.append("&radius=" + String.valueOf(radius));
           // sb.append("&keyword=" + URLEncoder.encode(keyword, "utf8"));   
            sb.append("&language=zh-TW");
            System.out.println(sb.toString());
            //String str="https://maps.googleapis.com/maps/api/place/search/json?language=zh-tw&sensor=true&key=AIzaSyB8QPf2KSpG_El4HN8IrvJ3GsT5YBsnrd8&keyword=%E7%BE%8E%E9%A3%9F&location=25.0688889,121.5330956&radius=500&pagetoken=ClRPAAAAEtQo4tKF13Md-vBee2QRZiY5oPbbgulpoVH-GJBybIiCglyyLu94DEhIM7CqYdgSpoDxcKMKe2Jad0aTU6HwIe-OVeEFd1Sc1fMXk0yWnKsSEHCG6iqLPQTAi8hrumoTQqoaFAY4ErgGdqHd6QcsS0QK1EhgKff8";
            
            URL url = new URL(sb.toString());
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                jsonResults.append(buff, 0, read);
            }
            
            System.out.println(jsonResults);
            
            
            try {
                // Create a JSON object hierarchy from the results
                JSONObject jsonObj = new JSONObject(jsonResults.toString());
                JSONArray predsJsonArray = jsonObj.getJSONArray("results");

                // Extract the Place descriptions from the results
                
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
                for (int i = 0; i < predsJsonArray.length(); i++) {
                	String name = predsJsonArray.getJSONObject(i).getString("name");
                	//if(this.httpget("http://tw.ipeen.lifestyle.yahoo.net/search/?kw="+name+"&c=1")){
                		System.out.println(name);
                	//}
                	//System.out.println(i);
                }
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
                
                
                
            } catch (JSONException e) {
                
            }
            
        } catch (MalformedURLException e) {

        } catch (IOException e) {

        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        


    }
	
	private boolean httpget(String str){
		
		try{
            Parser parser = new Parser( (HttpURLConnection) (new URL(str)).openConnection() );
            AndFilter filter = 
                    new AndFilter( 
                                  new TagNameFilter("div"), 
                                 new HasAttributeFilter("class","num") 
                  );
            NodeList nodes = parser.parse(filter);

            for (NodeIterator i = nodes.elements (); i.hasMoreNodes(); ) {
                Node node = i.nextNode();
                if(node.toPlainTextString().equals("符合條件共 0 筆結果"))return false;
                else return true;
                //return true;
            }  
            return false;
        }
        catch( Exception e ) { 
        	 System.out.println( "Exception:"+e );
        	return false;
           
        }
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new test2();
	}

}
